package com.bham.teamwork.filter;

import java.util.Date;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.bham.teamwork.utils.CookieUtil;
import com.bham.teamwork.utils.SecureTokenUtil;

/**
 * A filter to handle session problems
 * @author Rujia Li
 * @author Alessandro Pozzer
 * @author Federico Bacci
 *
 */
public class SSOFilter implements Filter {

	private String[] exceptionUrls=null;
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		String exceptionUrlStr=filterConfig.getInitParameter("exceptionUrl");
		if(exceptionUrlStr != null&&exceptionUrlStr.length() != 0){
			exceptionUrls=exceptionUrlStr.split(";");
		}
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) {
		try {
			//Exceptions to the URL do not need to be filtered through the login filter, such as the login page, no permissions page
			if(exceptionUrls!=null && exceptionUrls.length>0){
				String requestURI=((HttpServletRequest)request).getRequestURI();
				if(SecureTokenUtil.isExceptionURI(requestURI,exceptionUrls)){
					//logger.info("白名单["+requestURI+"],直接通过!");
					chain.doFilter(request, response);
					return;
				}
			}
			if(validataRequestPassedSsoFilter(request, response)) {//Through the single sign-on authentication
				chain.doFilter(request, response); //Through the validation, the normal filtering
				return;
			}else{
				redirect2ReloginPage((HttpServletRequest)request, (HttpServletResponse)response, chain);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	@Override
	public void destroy() {
	}


	private static String ssoCookieName = "ltapToken";

	public static boolean validataRequestPassedSsoFilter(ServletRequest request, ServletResponse response) throws Exception{
		
		if (!(request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse))  throw new ServletException("SSOFilter protects only HTTP resources");
		
		Long nowTime = (new Date().getTime())/1000; 	  //Get the current timestamp / 1000 only needs to be accurate to seconds
		
		HttpSession session=((HttpServletRequest)request).getSession();
		String cookieToken=CookieUtil.getCookieValue((HttpServletRequest) request, ssoCookieName);
		if(cookieToken == null || cookieToken.equals("")){ //If there is no cookie, all conversations are cleared and the login page is redirected
			return false;
		}

		String ltapToken="";
		try{
			ltapToken = SecureTokenUtil.analyzeLtapToken(cookieToken); //Decryption
		}catch (Exception e){
			return false;
		}
		String[] ltapTokenStr = ltapToken.split("\\|");
		Long satrtTime = Long.parseLong(ltapTokenStr[1]);
		Long endTime = Long.parseLong(ltapTokenStr[2]);
		String userId = ltapTokenStr[4];

		if(nowTime>endTime||endTime<satrtTime){
			return false;
		}
		
		String sessionUserId = session.getAttribute("SESSIONUSER")+"";
		if(!sessionUserId.equals(userId)){
			return false;
		}
		return true;
	}

	/**
	 * Jump to the page to re-landing
	 * @param request
	 * @param response
	 * @param chain
	 * @param noRedirectUrls
	 * @param loginType
	 * @throws Exception
	 */
	public static  void redirect2ReloginPage(HttpServletRequest request,HttpServletResponse response,FilterChain chain) throws Exception {
		HttpServletRequest req  = (HttpServletRequest)request;
		HttpServletResponse resp = (HttpServletResponse)response;
		String contextPath = req.getContextPath();
		resp.sendRedirect(contextPath+"/user/login.action?url="+ SecureTokenUtil.getRequestUrl((HttpServletRequest) request));
	}


	
	
}
